import { defineStore } from 'pinia'
import { adminLogin } from '../api/auth'
import { getAdminInfo } from '../api/user'

export const useAdminStore = defineStore('admin', {
    state: () => ({
        id: null,
        userName: '',
        token: '',
        adminInfo: null
    }),

    getters: {
        isLogin: (state) => !!state.token,
    },

    actions: {
        // 管理员登录
        async login(loginData) {
            try {
                const data = await adminLogin(loginData)
                this.setAdminInfo(data)
                return Promise.resolve(data)
            } catch (error) {
                return Promise.reject(error)
            }
        },

        // 设置管理员信息
        setAdminInfo(data) {
            this.id = data.id
            this.userName = data.userName
            this.token = data.token
            localStorage.setItem('adminToken', data.token)
        },

        // 获取管理员详细信息
        async fetchAdminInfo() {
            try {
                const data = await getAdminInfo()
                console.log('获取到的管理员信息:', data)
                // 安全地设置管理员信息
                if (data) {
                    this.adminInfo = data
                    return Promise.resolve(data)
                } else {
                    console.warn('未获取到管理员信息')
                    return Promise.reject(new Error('未获取到管理员信息'))
                }
            } catch (error) {
                console.error('获取管理员信息失败:', error)
                return Promise.reject(error)
            }
        },

        // 退出登录
        logout() {
            this.id = null
            this.userName = ''
            this.token = ''
            this.adminInfo = null
            localStorage.removeItem('adminToken')
        }
    }
})